"""
@File    :   boost_task.py
@Time    :   2024/03/18 16:01:25
@Author  :   Qrj
@Email   :   923207736@qq.com
@description   :   用户相关的funboost异步任务
"""

import ujson
from funboost import BoosterParams, BrokerEnum, ConcurrentModeEnum, boost
from redis.asyncio import Redis

from src.config import get_app_settings
from src.enums.redis_db import RedisDbNumEnum
from src.utils.uuid import UuidUtil

from .utils.image import ImageCaptchaUtil
from .utils.sliding_puzzle import SlidingPuzzleCaptchaUtil

# 获取应用配置
settings = get_app_settings()

# 创建Redis连接池
redis_pool = Redis(
    host=settings.redis_host,
    password=settings.redis_password,
    port=settings.redis_port,
    db=RedisDbNumEnum.cache_db.value,
    decode_responses=True,
)


@boost(
    BoosterParams(
        queue_name="queue_create_image_captcha_timed_task",
        broker_kind=BrokerEnum.REDIS_STREAM,
        concurrent_mode=ConcurrentModeEnum.ASYNC,
        log_level=30,
        create_logger_file=False,
    )
)
async def create_image_captcha_timed_handler():
    """定时创建图形验证码"""
    # 先从redis中查看一下当前hash表的长度(大于指定数量则不再插入)
    now_hash_table_len = await redis_pool.hlen(
        ImageCaptchaUtil.image_captcha_hash_table_name
    )
    if (
        now_hash_table_len
        <= settings.default_create_image_captcha_hash_table_max_couont
    ):
        # 构建批量插入的图像验证码数据
        batch_mapping = {}
        for i in range(settings.default_create_image_captcha_number - 1):
            (
                code_answer,
                images_base64_str,
            ) = await ImageCaptchaUtil.async_generate_image_captcha_base64()
            batch_mapping[UuidUtil.generate_uuid1()] = (
                code_answer + ":" + images_base64_str
            )
        await ImageCaptchaUtil.create_image_captcha(
            redis_pool, batch_mapping=batch_mapping
        )


@boost(
    BoosterParams(
        queue_name="queue_create_sliding_captcha_timed_task",
        broker_kind=BrokerEnum.REDIS_STREAM,
        concurrent_mode=ConcurrentModeEnum.ASYNC,
        log_level=30,
        create_logger_file=False,
    )
)
async def create_sliding_captcha_timed_handler():
    """定时创建滑块验证码"""
    # 先从redis中查看一下当前hash表的长度(大于指定数量则不再插入)
    now_hash_table_len = await redis_pool.hlen(
        SlidingPuzzleCaptchaUtil.sliding_puzzle_captcha_hash_table_name
    )
    if (
        now_hash_table_len
        <= settings.default_create_sliding_captcha_hash_table_max_couont
    ):
        # 构建批量插入的图像验证码数据
        batch_mapping = {}
        for i in range(settings.default_create_sliding_captcha_number - 1):
            (
                code_answer,
                base_img_base64_str,
                slide_base64_str,
            ) = await SlidingPuzzleCaptchaUtil.async_generate_captcha(
                SlidingPuzzleCaptchaUtil.random_get_sliding_image_path()
            )
            code_info = ujson.dumps(
                {
                    "code_answer": {"x": code_answer[0], "y": code_answer[1]},
                    "base_img_base64_str": base_img_base64_str,
                    "slide_base64_str": slide_base64_str,
                }
            )
            batch_mapping[UuidUtil.generate_uuid1()] = code_info
        await SlidingPuzzleCaptchaUtil.create_sliding_captcha(
            redis_pool, batch_mapping=batch_mapping
        )
